<?php
    include_once("db_connect.php");

if($_SESSION['logged']!='stat') {
    if(is_numeric($_POST["project_name"])){
	set_time_limit(300);
	$pro = $_POST["project_name"];
	$f=fopen($_FILES['file']['tmp_name'],"r");
	while(!feof($f)) {  
	    $str=fgets($f);
	    if(preg_match_all("/\d+/", $str, $matches)) 
	    {
		pg_exec("INSERT INTO public.caller_phones (pho_id, pro_id, pho_phone, pho_count, pho_done) 
			VALUES 
		        (nextval('caller_phones_pho_id_seq'), $pro, '".$matches[0][0]."', 0, 0)");
	    }
	}
	fclose($f);
	header("Location: /caller/import.php");
    }
    if(is_numeric($_GET["delid"])){
	pg_exec("DELETE FROM public.caller_phones WHERE pro_id = '".$_GET["delid"]."'");
	header("Location: /caller/import.php");
    }
}
    
?>

<?php
    include_once("menu.php");
?>

<h2>Import phones</h2>

<?
    if($_SESSION['logged']!='stat') :
?> 
<form method="post" enctype="multipart/form-data">

<?php
    $projects_sql = pg_exec('select * from public.caller_project');
    while($t = pg_fetch_array($projects_sql)){
	$projects[$t['pro_id']] = $t['pro_name'];
    }
?>

Select project: <select name="project_name">
<option value='0'>select project...</option>
<?php
    foreach($projects as $key_pr=>$project){
	echo "<option value='$key_pr'>$project</option>";
    }
?>
</select> <br />

Select file : <input type="file" name="file"><br />

<input type="submit" value="submit" name="submit"><br />

</form>
<?endif;?>

<table border=1>
<tr>
 <td>project</td>
 <td>count</td>
</tr>

<?php
    $new = pg_exec('select COUNT(*) as cnt, pro_id from public.caller_phones GROUP BY pro_id');
    while($t = pg_fetch_array($new)){
	$new2 = pg_exec('select pro_name from public.caller_project WHERE pro_id='.$t['pro_id'].'');
	$t2 = pg_fetch_array($new2);
	echo "<tr>";
	echo "<td>".$t2['pro_name']."</td>";
	echo "<td>".$t['cnt']."</td>";
	echo '<td><a href="phones.php?project='.$t['pro_id'].'">view</a></td>';
	if($_SESSION['logged']=='root') {
	    echo '<td><a href="?delid1='.$t['pro_id'].'">delete</a></td>';
	}
	echo "</tr>";
    }
?>

</table>

<?php    
    include_once("db_disconnect.php");
?>